package com.youlai.caffeine.dao;

import com.youlai.caffeine.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 模拟数据库操作
 * @author zc
 * @date 2023-03-28 23:59
 */
@Component
@Slf4j
public class UserRepository {

    List<User> users = new ArrayList<User>();


    @PostConstruct
    public void init() {
        users.add(new User(1L, "张三", "admin"));
        users.add(new User(2L, "李四", "admin"));
        users.add(new User(3L, "王五", "admin"));
        users.add(new User(4L, "赵六", "user"));
        users.add(new User(5L, "田七", "user"));
    }

    public User findByRole(String role) {
        log.info("查询数据库");
        return users.stream().filter(user -> user.getRole().equals(role)).findFirst().get();
    }

    public User save(User user) {
        log.info("保存数据库");
        users.add(user);
        return user;
    }

    public User findById(Long id) {
        log.info("查询数据库");
        return users.stream().filter(user -> user.getId().equals(id)).findFirst().get();
    }

    public List<User> getUsersByRole(String role) {
       log.info("查询数据库");
        Optional<User> any = users.stream().filter(user -> user.getRole().equals(role)).findAny();
        List<User> users = new ArrayList<>();
        users.add(any.get());
        return users;
    }

    public void deleteById(Long id) {
        log.info("删除数据库");
        users.removeIf(user -> user.getId().equals(id));
    }
}
